<template>
  <div>
    <TopFilter ref="filter" :list="topFilterList" :cols="3" :isSubmitBtn="false" :collapse="false" @filterChange="changeHandle" @onCollapse="collapseHandle"></TopFilter>
    <FilterTable
      ref="table"
      :columns="columns"
      columnsRef="partAccessAccessInventoryOldindex"
      :isSelectColumn="false"
      :onSyncTableData="getAll"
      :params="fetchParams"
      :datakey="'rows'"
      :onColumnsChange="columns => (this.columns = columns)"
    >
      <template slot="controls">
        <el-button size="small" type="primary" icon="el-icon-plus" @click="addHandle">新增</el-button>
      </template>
    </FilterTable>
    <div style="text-align:center">
      <el-button size="small" :disabled="flag1" type="primary" icon="el-icon-plus" @click="getDataAdd">新建</el-button>
      <el-button size="small" :disabled="flag2" @click="save">保存</el-button>
      <el-button size="small" :disabled="flag3" @click="check">盘点确认</el-button>
      <el-button size="small" :disabled="flag4" @click="reset">取消</el-button>
      <el-button size="small" :disabled="flag5">打印</el-button>
      <el-button size="small" :disabled="flag6" @click="del">作废</el-button>
    </div>
    <Drawer :visible.sync="visible" :title="dialogTitle" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <select :type="handleType" :rowData="formData" @close="closeHandler" @getData="getData" />
    </Drawer>
    <Drawer :visible.sync="visibleAdd" :title="dialogTitleAdd" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <add :type="handleTypeAdd" @close="closeHandlerAdd" @getDataAdd="getDataAdd" />
    </Drawer>
    <Drawer :visible.sync="visibleEdit" :title="dialogTitleEdit" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <editModal :type="handleTypeEdit" :rowData="formDataEdit" @close="closeHandlerEdit" @getDataEditAdd="getDataEditAdd" />
    </Drawer>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import { findAllInventoryItemInfoById, saveInventoryInfo, btnDel, btnConfirm, deleteTableData, saveBlankInventoryNo } from '@/api/part/access/accessInventory';
import select from './tabs/select';
import add from './tabs/add';
import editModal from './tabs/edit';

export default {
  name: 'Brand',
  components: {
    select,
    add,
    editModal
  },
  mixins: [dictionary],
  data() {
    this.BaseTable = null;
    this.Filter = null;
    this.conf = { add: '新建', edit: '编辑', show: '显示' };
    return {
      topFilterList: this.createTopFilterList(),
      fetchParams: {},
      formDataEdit: {},
      resultData: {},
      handleTypeAdd: '',
      all: [],
      dialogTitleEdit: '',
      handleTypeEdit: '',
      visibleEdit: false,
      visibleAdd: false,
      visible: false,
      dialogTitle: '',
      columns: this.createTableColumns(),
      handleType: '',
      dialogTitleAdd: '',
      formData: {},
      flag1: false,
      flag2: false,
      flag3: false,
      flag4: false,
      flag5: false,
      flag6: false,
      flag7: false
    };
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
    this.Filter = this.$refs.filter;
    this.flag2 = true;
    this.flag3 = true;
    this.flag4 = false;
    this.flag5 = true;
    this.flag6 = true;
    this.flag7 = true;
  },
  methods: {
    createTopFilterList() {
      return [
        {
          type: 'INPUT',
          label: '盘点单号',
          fieldName: 'inventoryNo',
          readonly: false,
          unitRender: () => {
            return (
              <div>
                <el-button size="small" type="primary" onClick={() => this.searchInven()}>
                  搜索
                </el-button>
              </div>
            );
          }
        },
        {
          type: 'INPUT',
          label: '经手人',
          fieldName: 'handler',
          disabled: true
        },
        {
          type: 'DATE',
          label: '盘点日期',
          fieldName: 'inventoryDate',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '备注',
          fieldName: 'remark',
          disabled: true,
          selfCols: 3
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          width: 70,
          sorter: true,
          render: props => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.update(props.row)}>
                  编辑
                </el-button>
                <el-button size="mini" type="text" onClick={() => this.delete(props.row)}>
                  删除
                </el-button>
              </div>
            );
          }
        },
        {
          title: '仓库',
          dataIndex: 'storageName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '库位',
          dataIndex: 'storagePositionCode',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '配件代码',
          dataIndex: 'partNo',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '配件名称',
          dataIndex: 'partName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        // {
        //   title: '当前库存',
        //   dataIndex: 'currentStock',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input'
        // },
        {
          title: '实际库存',
          dataIndex: 'realStock',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '清点数量',
          dataIndex: 'checkQuantity',
          sorter: true,
          filter: true
        },
        {
          title: '差异数量',
          dataIndex: 'profitLossQuantity',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '成本单价',
          dataIndex: 'costPrice',
          sorter: true,
          filter: true,
          filterType: 'input'
        }
      ];
    },
    closeHandlerEdit() {
      this.visibleEdit = false;
    },
    getDataEditAdd(x, y) {
      console.log(x, y);
      for (let key in this.formDataEdit) {
        if (key == 'checkQuantity') {
          this.formDataEdit[key] = y.checkQuantity;
        }
        if (key == 'profitLossQuantity') {
          this.formDataEdit[key] = y.profitLossQuantity;
        }
      }
      this.visibleEdit = false;
    },
    async delete(row) {
      this.$confirm('是否确定删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          console.log(1);
          this.Filter.SUBMIT_FORM();
          console.log(row);
          // console.log(this.fetchParams);
          // let json = Object.assign({},{inventoryNo:this.fetchParams.inventoryNo},row);
          //  console.log(json);
          //  deleteTableData(json);
          this.BaseTable.EXECUTE_DELETE([row]);
          //  this.reSearch(json.inventoryNo, 0);
          this.$emit('close', false);
        })
        .catch(() => {
          // this.$notify.info({title: '提示信息',message:'已取消删除'});
        });
    },
    update(row) {
      this.visibleEdit = true;
      this.formDataEdit = row;
    },
    searchInven() {
      console.log(1);
      this.handleType = 'add';
      this.visible = true;
    },
    addHandle() {
      this.handleTypeAdd = 'add';
      this.dialogTitleAdd = `${this.conf[this.handleTypeAdd]}配件盘点单`;
      this.visibleAdd = true;
    },
    changeHandle(val) {
      this.fetchParams = Object.assign({}, val);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    async getDataAdd() {
      let res = await saveBlankInventoryNo({});
      console.log('blankInventory', res);
      this.flag1 = this.flag3 = this.flag5 = true;
      this.flag2 = this.flag4 = this.flag6 = this.flag7 = false;
      this.topFilterList[0].initialValue = res.data.inventoryNo;
      this.topFilterList[1].initialValue = res.data.handler;
      this.topFilterList[2].initialValue = res.data.inventoryDate;
    },
    setPartList() {
      console.log(flag, json, 888);
      if (json && json.length > 0) {
        for (let key in json[0]) {
          for (let i = 0; i < this.topFilterList.length; i++) {
            if (key == this.topFilterList[i].fieldName) this.topFilterList[i].initialValue = json[0][key];
          }
        }
      }
      console.log(json[0].inventoryNo);
      this.reSearch(json[0].inventoryNo, 0);
      this.visible = false;
    },
    getData(flag, json) {
      console.log(flag, json, 888);
      if (json && json.length > 0) {
        for (let key in json[0]) {
          for (let i = 0; i < this.topFilterList.length; i++) {
            if (key == this.topFilterList[i].fieldName) this.topFilterList[i].initialValue = json[0][key];
          }
        }
        this.flag1 = this.flag3 = this.flag5 = true;
        this.flag2 = this.flag4 = this.flag6 = this.flag7 = false;
        this.topFilterList[0].readonly = true;
        this.topFilterList[1].disabled = true;
        this.topFilterList[2].disabled = true;
        this.topFilterList[3].disabled = true;
      }
      console.log(json[0].inventoryNo);
      this.reSearch(json[0].inventoryNo, 0);
      this.visible = false;
    },
    async reSearch(a, b) {
      console.log(a, b);
      let js = {
        id: a,
        num: b
      };
      console.log(js);
      this.resultData = await findAllInventoryItemInfoById(js);
      this.BaseTable.EXECUTE_DELETE(this.all);
      this.BaseTable.EXECUTE_INSERT(this.resultData.data.rows);
    },
    showHandler() {
      this.dialogTitle = `${this.conf[this.handleType]}品牌`;
      this.visible = true;
    },
    closeHandler(val, type) {
      this.visible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    closeHandlerAdd(val, type) {
      this.visibleAdd = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    save() {
      console.log(this.Filter);
      this.Filter.SUBMIT_FORM();
      let arr = this.all;
      let json = Object.assign({}, this.fetchParams, {
        dms_details: arr
      });
      console.log(json);
      this.$confirm('是否确定保存？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let res = saveInventoryInfo(json);
        console.log(res, 12345);
        if (res == 0) {
          // 保存成功
        } else {
          // this.saveError();
        }
      });
    },
    del() {
      this.$confirm('是否确定删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.Filter.SUBMIT_FORM();
          let json = Object.assign({}, this.fetchParams, {
            dms_details: this.resultData.data.rows
          });
          console.log(json);
          let res = btnDel(json);
          console.log(res);
          this.reSearch(this.fetchParams.inventoryNo, 0);
        })
        .catch(() => {
          // this.$notify.info({title: '提示信息',message:'已取消删除'});
        });
    },
    async check() {
      this.Filter.SUBMIT_FORM();
      let json = Object.assign({}, this.fetchParams, {
        dms_details: this.resultData.data.rows
      });
      let res = await btnConfirm(json);
      console.log(res);
    },
    inData() {
      console.log(123);
      let value = '';
      for (let i = 0; i < this.all.length; i++) {
        let arr = this.all[i];
        for (let key in arr) {
          if (key == 'realStock') {
            value = arr[key];
          }
        }
        for (let key in arr) {
          if (key == 'checkQuantity') {
            arr[key] = value;
          }
          if (key == 'profitLossQuantity') {
            arr[key] = 0;
          }
        }
      }
      console.log(this.all);
    },
    change(row) {
      // let regex = /^([0-9 ]+)(\.[0-9 ]+)?$/;
      // this.flag2 = !regex.test(row.checkQuantity);
      // if(!this.flag2){
      //   let value = '';
      //   for(let key in row){
      //     if(key == 'realStock'){
      //       value = row[key];
      //     }
      //   }
      //   if(value != ''){
      //     let a = row.checkQuantity - value;
      //     for(let key in row){
      //       if(key == 'profitLossQuantity'){
      //         row[key] = a;
      //       }
      //     }
      //   }
      // }else{
      //   this.error();
      //   return;
      // }
    },
    error() {
      this.$notify.error({
        title: '错误',
        message: '填写错误，此处必须是数字'
      });
    },
    saveError() {
      this.$notify.error({
        title: '错误',
        message: '操作失败，该数据已经保存过'
      });
    },
    getAll(val) {
      console.log(val);
      this.all = val;
    },
    reset() {
      this.flag1 = this.flag4 = false;
      this.flag2 = this.flag3 = this.flag5 = this.flag6 = this.flag7 = true;
      this.BaseTable.EXECUTE_DELETE(this.all);
      this.Filter.RESET_FORM();
    }
  }
};
</script>

<style lang="less" scoped></style>
